package org.xxpay.pay.channel.yunsfpay;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.domain.api.AbstractRes;
import org.xxpay.core.common.domain.api.ApiBuilder;
import org.xxpay.core.common.domain.api.PayRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.XXPayUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.channel.yunsfpay.util.PayUtils;
import org.xxpay.pay.mq.BaseNotify4MchPay;

import java.text.DecimalFormat;
import java.util.Map;

/**
 * @Description 云闪付支付接口
 * @author hjj
 * @EditDate  2019年1月18日 上午11:19:37
 *
 */
@Service
public class YunsfpayPaymentService extends BasePayment {

    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    private static final MyLog _log = MyLog.getLog(YunsfpayPaymentService.class);

    @Override
    public String getChannelName() {
        return YunsfpayConfig.CHANNEL_NAME;
    }

    /**
     * 支付
     *
     * @param payOrder
     * @return
     */
    @Override
    public AbstractRes pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        switch (channelId) {
            // 云闪付扫码
            case YunsfpayConfig.PAY_CHANNEL_YUNSFPAY_QR:
                return dopayReq(payOrder, "1");

            default: return ApiBuilder.bizError("不支持的支付渠道[channelId=" + channelId + "]");
        }
    }
    public static void main(String[] args) {

        JSONObject retObj = new JSONObject();
        double amount = 0.01;
        // 云闪付流程 1 http://app.vp552.cn:38581/getpay?money=0.01&mark=a2015d0002&type=unionpay&&tdsourcetag=s_pctim_aiomsg
        String baseReqUrl = "http://app.vp552.cn:38581/getpay";
        baseReqUrl = baseReqUrl+"?money="+new DecimalFormat("0.00").format(amount)+"&mark="+System.currentTimeMillis()+"&type=unionpay&tdsourcetag=s_pctim_aiomsg";
        _log.info("yunsfpay-请求报文：" + baseReqUrl);
        try {
            // 请求响应结果
            String response = XXPayUtil.call4Post(baseReqUrl);
            _log.info("yunsfpay-响应结果：" + response);
        } catch (Exception e) {
            _log.error(e, "");

        }


    }

    /**
     * 支付下单接口
     *
     * @param payOrder
     * @return
     */
    public AbstractRes dopayReq(PayOrder payOrder, String type) {
        _log.info("yunsfpay-渠道交易下单开始");
        YunsfpayConfig yunsfpayConfig = new YunsfpayConfig(getPayParam(payOrder));
        PayRes retObj = ApiBuilder.buildSuccess(PayRes.class);
        // 云闪付流程 1 http://app.vp552.cn:38581/getpay?money=0.01&mark=a2015d0002&type=unionpay&&tdsourcetag=s_pctim_aiomsg
        // 支付宝: alipay
        // 微信: wechat
        // 云闪付: unionpay
        // 请求网关地址
        String baseReqUrl = yunsfpayConfig.getReqUrl();
        // get请求全地址
        baseReqUrl = baseReqUrl+"?money="+new DecimalFormat("0.00").format(payOrder.getAmount() / 100.0)+"&mark="+payOrder.getPayOrderId()+"&type=unionpay&tdsourcetag=s_pctim_aiomsg";
        _log.info("yunsfpay-请求报文：" + baseReqUrl);
        try{
            // 请求响应结果
            String response = XXPayUtil.call4Get(baseReqUrl);
            _log.info("yunsfpay-响应结果：" + response);
            if(response != "" && !response.equals("")){
                Map<String,Object> resmap = PayUtils.parseJSON2Map(response);
                if("获取成功".equals(resmap.get("msg"))){
                    String payUrl = resmap.get("payurl").toString();
                    retObj.setPayOrderId(payOrder.getPayOrderId()); // 设置支付订单ID
                    retObj.setQrInfo(payUrl, genCodeImgUrl(payUrl));

                    int result = commonService.payOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
                    _log.info("[{}]更新订单状态为支付中:payOrderId={},prepayId={},result={}", getChannelName(), payOrder.getPayOrderId(),
                            "", result);
                    return retObj;
                }else{
                    return ApiBuilder.bizError("获取支付信息失败!");
                }

            }else{
                return ApiBuilder.bizError("请求失败!");
            }
        } catch (Exception e) {
            _log.error(e, "");
            return ApiBuilder.bizError("操作异常!");
        }
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public QueryRetMsg query(PayOrder payOrder) {
        //上游没有查询接口
        return QueryRetMsg.waiting();
    }

}